import Vue from 'vue';
import VueRouter from 'vue-router';
import Layout from '@/components/Layout.vue';
// vuex的store实例对象
import store from '@/store'
import static_routes from './static_routes';
import { Notification } from 'element-ui'
import global from '@/plugins/global';
Vue.use(VueRouter)

const router = new VueRouter({
	routes: static_routes,
});

let checkRouteExist = (route) => {
	// 获取所有路由
	let routes = router.getRoutes();
	// 判断是否存在
	return routes.some((item) => item.name === route.name);
}
// 全局--前置守卫
router.beforeEach(async(to, from, next) => {
	// 查询静态路由,是否匹配目标地址
	console.log('目标地址', to);
	let target_route = static_routes.find((route) => route.name === to.name)
	// 不是静态路由
	if (!target_route) {
		// 提取token
		let access_token = sessionStorage.access_token;
		// 未登录
		if (!access_token) {
			Notification.error({
				title: '错误',
				message: '禁止访问，请登录账户'
			});
			next({ path: '/login', query: { redirect: to.fullPath } });
			return;
		}
		// 登录状态
		if (global.is_route_unload) {
			let role_id = sessionStorage.role_id;
			// 加载路由权限
			await store.dispatch('role/load_route_permission', { role_id });
			// 获取store中的getters路由对象
			let route_tree = store.getters['role/route_tree']
			// 动态添加路由
			route_tree.forEach((route) => {
				// 检查是否存在
				let isExist = checkRouteExist(route);
				if (isExist) {
					return;
				}
				router.addRoute(route);
			});
			// 最后添加404
			router.addRoute({
				path: '*',
				name: 'NotFound',
				meta: {
					require_auth: false,
					route_name: '访问错误',
				},
				component: () => import( /* webpackChunkName: "NotFound" */ '@/views/NotFound.vue')
			});
			// 修改路由状态
			global.is_route_unload = false;
			// 触发重定向
			return next({ ...to, replace: true });
		}

	}
	// 判断是否需要登录认证
	let is_require_auth = target_route?.meta.require_auth;
	// 无需认证
	if (!is_require_auth) {
		return next();
	}
});
// 全局--解析守卫
// 全局--后置守卫
router.afterEach((to, from) => {
	let { route_name } = to.meta;
	document.title = route_name ? `${route_name}--CMS管理系统` : `CMS管理系统`;
})
export default router
